/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.dishes;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.Dishes;
import com.qinyeit.serviceapp.entity.MaterialCategory;
import com.qinyeit.serviceapp.service.dishes.DishesService;
import com.qinyeit.serviceapp.service.materials.MaterialCategoryService;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.DishesCategory;
import com.qinyeit.serviceapp.service.dishes.DishesCategoryService;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * ClassName: DishesCategorysController <br/>
 * Function: dishesCategory [菜品分类] <br/>
 * date: 2018-11-23 11:05:47 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/dishes/dishesCategorys")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_dishesCategory:read",name ="菜品分类",deleteAble = false)
public class DishesCategorysController extends BaseManagementController{

	@Autowired
	private DishesCategoryService dishesCategoryService;
	@Autowired
	private DishesService dishesService;
	@Autowired
	private MaterialCategoryService materialCategoryService;

	private final String [] keys = {"id","storeId","no","name","state","weight","remark"};

//    @RequiresPermissions("management_dishesCategory:show")
    @RequiresPermissions("management_dishes:show")
    @PermissionInfo(code = "management_dishesCategory:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable,Long storeId){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        searchable.addSearchParam("no_ne","00000");
        searchable.addSearchParam("storeId_eq",storeId);
        Page<DishesCategory> dishesCategoryPage = dishesCategoryService.findAll(searchable);
        return ok("查询成功", JSONUtils.include(dishesCategoryPage, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        DishesCategory category = new DishesCategory();
        category.setNo(dishesCategoryService.getNextNo("01",CurrentAccountUtils.getAuthenticatedMerchantGroupID()));
        map.setv("dishesCategory",JSONUtils.include(category, keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesCategory:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid DishesCategory dishesCategory, BindingResult bindingResult){
//        if(dishesCategoryService.exists(buildExists(null, "no", dishesCategory.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        Searchable searchable = SearchableUtils.buildExists(dishesCategory.getId(), "name", dishesCategory.getName());
        searchable.addSearchParam("storeId_eq",dishesCategory.getStoreId());
        if(dishesCategoryService.exists(searchable)){
            return fail("名称已经存在");
        }
        if(StringUtils.isBlank(dishesCategory.getName())){
            return fail("请输入名称后保存");
        }
        dishesCategory.setUuid(LocalUtils.getUUID());
        dishesCategory.setUpdateTimestamp(DateUtils.current());
        dishesCategory.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        dishesCategoryService.save(dishesCategory);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute DishesCategory dishesCategory){
        return ok("查询成功", JSONUtils.include(dishesCategory, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute DishesCategory dishesCategory){
        QyMap map=QyMap.NEW();
        map.setv("dishesCategory",JSONUtils.include(dishesCategory, keys));
        initFormDate(map); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesCategory:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid DishesCategory dishesCategory,BindingResult bindingResult){
//        if(dishesCategoryService.exists(buildExists(null, "no", dishesCategory.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        Searchable searchable = SearchableUtils.buildExists(dishesCategory.getId(), "name", dishesCategory.getName());
        searchable.addSearchParam("storeId_eq",dishesCategory.getStoreId());
        if(dishesCategoryService.exists(searchable)){
            return fail("名称已经存在");
        }
        if(StringUtils.isBlank(dishesCategory.getName())){
            return fail("请输入名称后保存");
        }
        dishesCategory.setUpdateTimestamp(DateUtils.current());
        dishesCategory.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        dishesCategoryService.update(dishesCategory);
        //修改原料类别
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("dishesCategoryId_eq",dishesCategory.getId());
        MaterialCategory category = materialCategoryService.findOne(searchable);
        if(category!=null){
            category.setNo(dishesCategory.getNo());
            category.setUpdateTimestamp(dishesCategory.getUpdateTimestamp());
            category.setName("S"+dishesCategory.getName());
            category.setParentId(0L);
            category.setParentIds("0/");
            materialCategoryService.update(category);
        }
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_dishes:edit")
    @PermissionInfo(code = "management_dishesCategory:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("category.id_eq",id);
        Long count = dishesService.count(searchable);
        if(count>0){
            return fail("删除失败，该类别已使用");
        }
        DishesCategory category = dishesCategoryService.findById(id);
        category.setUpdateTimestamp(DateUtils.current());
        dishesCategoryService.update(category);
        dishesCategoryService.logicDelete(id);
        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            DishesCategory dishesCategory = dishesCategoryService.findById(Long.valueOf(id));
            model.addAttribute(dishesCategory);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){

    }

}